package cn.jaye.fabric.common.interceptor;

/**
 * @author Jaye
 * @create 2017-12-25 11:16
 */

import cn.jaye.fabric.common.constant.ExceptionEnum;
import cn.jaye.fabric.common.constant.Global;
import cn.jaye.fabric.common.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class SecurityInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.getSession().setAttribute("username", Global.TEST_USERNAME);
        request.getSession().setAttribute("password", Global.TEST_PASSWORD);
        request.getSession().setAttribute("orgId", Global.TEST_ORGID);
        String username = (String) request.getSession().getAttribute("username");
        String password = (String) request.getSession().getAttribute("password");
        String orgId = (String) request.getSession().getAttribute("orgId");
        if (username != null && StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && StringUtils.isNotBlank(orgId)) {
            return true;
        }
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(ResultUtil.error(ExceptionEnum.USER_NOLOGIN));
            out.flush();
            out.close();
        } else {
            response.sendRedirect(request.getContextPath() + "/login");
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

}
